﻿using Newtonsoft.Json;
using System;

namespace TCSF_Licence
{
    public class JsonSerialization
    {
        /// <summary>
        /// 将一个实体序列化
        /// </summary>
        /// <param name="model">对象实体</param>
        /// <returns></returns>
        public static string JsonSerializationFun(object model)
        {
            Newtonsoft.Json.Converters.IsoDateTimeConverter iso = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            JsonSerializerSettings jss = new JsonSerializerSettings() { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(), Converters = { iso }, DateFormatHandling = DateFormatHandling.IsoDateFormat };
            iso.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string jsonString = JsonConvert.SerializeObject(model, jss);
            return jsonString;
        }

        /// <summary>
        /// 将Json字符串反序列化为对象
        /// </summary>
        /// <param name="jsonString">Json字符串</param>
        /// <returns>实体</returns>
        public static T JsonDeserializationFun<T>(string jsonString)
        {
            try
            {
                T t = JsonConvert.DeserializeObject<T>(jsonString);
                return t;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return default(T);
            }
        }
    }
}